#pragma once
#include "Server.hpp"
#include <fstream>
#include <regex>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

std::unordered_map<int, std::string> _statu_msg = {
    {100,  "Continue"},
    {101,  "Switching Protocols"},
    {102,  "Processing"},
    {103,  "Early Hints"},
    {200,  "OK"},
    {201,  "Created"},
    {202,  "Accepted"},
    {203,  "Non-Authoritative Information"},
    {204,  "No Content"},
    {205,  "Reset Content"},
    {206,  "Partial Content"},
    {207,  "Multi-Status"},
    {208,  "Already Reported"},
    {226,  "IM Used"},
    {300,  "Multiple Choice"},
    {301,  "Moved Permanently"},
    {302,  "Found"},
    {303,  "See Other"},
    {304,  "Not Modified"},
    {305,  "Use Proxy"},
    {306,  "unused"},
    {307,  "Temporary Redirect"},
    {308,  "Permanent Redirect"},
    {400,  "Bad Request"},
    {401,  "Unauthorized"},
    {402,  "Payment Required"},
    {403,  "Forbidden"},
    {404,  "Not Found"},
    {405,  "Method Not Allowed"},
    {406,  "Not Acceptable"},
    {407,  "Proxy Authentication Required"},
    {408,  "Request Timeout"},
    {409,  "Conflict"},
    {410,  "Gone"},
    {411,  "Length Required"},
    {412,  "Precondition Failed"},
    {413,  "Payload Too Large"},
    {414,  "URI Too Long"},
    {415,  "Unsupported Media Type"},
    {416,  "Range Not Satisfiable"},
    {417,  "Expectation Failed"},
    {418,  "I'm a teapot"},
    {421,  "Misdirected Request"},
    {422,  "Unprocessable Entity"},
    {423,  "Locked"},
    {424,  "Failed Dependency"},
    {425,  "Too Early"},
    {426,  "Upgrade Required"},
    {428,  "Precondition Required"},
    {429,  "Too Many Requests"},
    {431,  "Request Header Fields Too Large"},
    {451,  "Unavailable For Legal Reasons"},
    {501,  "Not Implemented"},
    {502,  "Bad Gateway"},
    {503,  "Service Unavailable"},
    {504,  "Gateway Timeout"},
    {505,  "HTTP Version Not Supported"},
    {506,  "Variant Also Negotiates"},
    {507,  "Insufficient Storage"},
    {508,  "Loop Detected"},
    {510,  "Not Extended"},
    {511,  "Network Authentication Required"}
};

std::unordered_map<std::string, std::string> _mime_msg = {
    {".aac",        "audio/aac"},
    {".abw",        "application/x-abiword"},
    {".arc",        "application/x-freearc"},
    {".avi",        "video/x-msvideo"},
    {".azw",        "application/vnd.amazon.ebook"},
    {".bin",        "application/octet-stream"},
    {".bmp",        "image/bmp"},
    {".bz",         "application/x-bzip"},
    {".bz2",        "application/x-bzip2"},
    {".csh",        "application/x-csh"},
    {".css",        "text/css"},
    {".csv",        "text/csv"},
    {".doc",        "application/msword"},
    {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot",        "application/vnd.ms-fontobject"},
    {".epub",       "application/epub+zip"},
    {".gif",        "image/gif"},
    {".htm",        "text/html"},
    {".html",       "text/html"},
    {".ico",        "image/vnd.microsoft.icon"},
    {".ics",        "text/calendar"},
    {".jar",        "application/java-archive"},
    {".jpeg",       "image/jpeg"},
    {".jpg",        "image/jpeg"},
    {".js",         "text/javascript"},
    {".json",       "application/json"},
    {".jsonld",     "application/ld+json"},
    {".mid",        "audio/midi"},
    {".midi",       "audio/x-midi"},
    {".mjs",        "text/javascript"},
    {".mp3",        "audio/mpeg"},
    {".mpeg",       "video/mpeg"},
    {".mpkg",       "application/vnd.apple.installer+xml"},
    {".odp",        "application/vnd.oasis.opendocument.presentation"},
    {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt",        "application/vnd.oasis.opendocument.text"},
    {".oga",        "audio/ogg"},
    {".ogv",        "video/ogg"},
    {".ogx",        "application/ogg"},
    {".otf",        "font/otf"},
    {".png",        "image/png"},
    {".pdf",        "application/pdf"},
    {".ppt",        "application/vnd.ms-powerpoint"},
    {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar",        "application/x-rar-compressed"},
    {".rtf",        "application/rtf"},
    {".sh",         "application/x-sh"},
    {".svg",        "image/svg+xml"},
    {".swf",        "application/x-shockwave-flash"},
    {".tar",        "application/x-tar"},
    {".tif",        "image/tiff"},
    {".tiff",       "image/tiff"},
    {".ttf",        "font/ttf"},
    {".txt",        "text/plain"},
    {".vsd",        "application/vnd.visio"},
    {".wav",        "audio/wav"},
    {".weba",       "audio/webm"},
    {".webm",       "video/webm"},
    {".webp",       "image/webp"},
    {".woff",       "font/woff"},
    {".woff2",      "font/woff2"},
    {".xhtml",      "application/xhtml+xml"},
    {".xls",        "application/vnd.ms-excel"},
    {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml",        "application/xml"},
    {".xul",        "application/vnd.mozilla.xul+xml"},
    {".zip",        "application/zip"},
    {".3gp",        "video/3gpp"},
    {".3g2",        "video/3gpp2"},
    {".7z",         "application/x-7z-compressed"}
};

/*-------------------------------Util工具类--------------------------------------------
作用：封装一些常用的功能性函数*/
class Util
{
public:
    // 字符串分割，给定字符串src，在其当中以sep进行分割，分割出来的字符串放入array中
    static size_t Split(const std::string &src,const std::string &sep,std::vector<std::string> *array)
    {
        size_t offset = 0;
        while(offset < src.size())
        {
            size_t pos = src.find(sep,offset);// 从offset处开始向后查找sep
            if(pos == std::string::npos)// 没有找到sep
            {
                array->push_back(src.substr(offset));// 从offset开始作为一个整体放入array
                return array->size();
            }
            if(pos == offset)// offset指向的位置就是sep的起始位置
            {
                offset = pos + sep.size();
                continue;// 跳过
            }
            array->push_back(src.substr(offset,pos - offset));
            offset = pos + sep.size();
        }
        return array->size();
    }

    static bool ReadFile(const std::string &filename,std::string *buf)// 读取文件数据
    {
        std::ifstream ifs(filename,std::ios::binary);
        if(ifs.is_open() == false)
        {
            DEBUG_LOG("OPEN FILE ERROR: %s",filename.c_str());
            return false;
        }
        size_t fsize = 0;
        ifs.seekg(0,ifs.end);// 偏移到文件末尾
        fsize = ifs.tellg();// 计算文件大小
        ifs.seekg(0,ifs.beg);// 便宜到文件起始
        buf->resize(fsize);
        ifs.read(&(*buf)[0],fsize);
        if(ifs.good() == false)
        {
            DEBUG_LOG("READ FILE ERROR: %s",filename.c_str());
            ifs.close();
            return false;
        }
        ifs.close();
        return true;
    }

    static bool WriteFile(const std::string &filename,const std::string &buf)// 向文件写入数据
    {
        std::ofstream ofs(filename,std::ios::binary | std::ios::trunc);// 覆盖式写入
        if(ofs.is_open() == false)
        {
            DEBUG_LOG("OPEN FILE ERROR: %s",filename.c_str());
            return false;
        }
        ofs.write(buf.c_str(),buf.size());
        if(ofs.good() == false)
        {
            DEBUG_LOG("READ FILE ERROR: %s",filename.c_str());
            ofs.close();
            return false;
        }
        ofs.close();
        return true;
    }

    // URL编码，bool类型参数意思为是否要将空格转换成加号
    static std::string UrlEncode(const std::string &url,bool conver_space_to_plus)
    {
        std::string res;
        for(auto &c:url)
        {
            if(c == '.' || c == '-' || c == '_' || c == '~' || isalnum(c))// 这些都是绝对不编码的
            {
                res += c;
                continue;
            }
            if(c == ' ' && conver_space_to_plus == true)// 如果设置了空格转换成加号(这个情况发生在URL的查询字符串中)
            {
                res += '+';
                continue;
            }
            // 剩下的字符都要编码，编码的格式的为"%HH"，H代码一个十六进制数
            char tmp[4] = {0};
            snprintf(tmp,4,"%%%02X",c);
            res += tmp;
        }
        return res;
    }

    static std::string UrlDecode(const std::string &url,bool conver_plus_to_space)// URL解码
    {
        std::string res;
        for(int i=0;i<url.size();i++)
        {
            if(url[i] == '+' && conver_plus_to_space == true)// 如果加号要转换成空格
            {
                res += ' ';
                continue;
            }
            if(url[i] == '%' && (i + 2) < url.size())
            {
                char v1 = HEXTOI(url[i + 1]);
                char v2 = HEXTOI(url[i + 2]);
                char v = v1 * 16 + v2;
                res += v;
                i += 2;
                continue;
            }
            res += url[i];// 保存结果
        }
        return res;// 返回结果
    }

    static char HEXTOI(char c)// 将十六进制的数转换为十进制的字符
    {
        if(c >= '0' && c <= '9') 
            return c - '0';// c就是一个十进制的字符
        if(c >= 'a' && c <= 'z')
            return c - 'a' + 10;// 假设c='a'，c - 'a' = 1，但是'a'对应的十进制为11，所以要+10
        if(c >= 'A' && c <= 'Z')
            return c - 'A' + 10;
        return -1;
    }

    static std::string StatuDesc(int statu)// 根据响应状态码获取响应描述
    {
        auto it = _statu_msg.find(statu);
        if(it != _statu_msg.end())
        {
            return it->second;
        }
        return "Unknow";
    }

    static std::string ExtMime(const std::string &filename)// 根据文件名后缀获取对应的mime
    {
        size_t pos = filename.find_last_of('.');
        if(pos == std::string::npos)
        {
            return "application/octet-stream";// 没有找到'.'，就是二进制流
        }
        std::string ext = filename.substr(pos);
        auto it = _mime_msg.find(ext);
        if(it == _mime_msg.end())// 如果并没有后缀名对应的mime
        {
            return "application/octet-stream";
        }
        return it->second;
    }

    static bool IsDirectory(const std::string &filename)// 判断一个文件是否是目录
    {
        struct stat st;
        int ret = stat(filename.c_str(),&st);
        if(ret < 0)
        {
            return false;
        }
        return S_ISDIR(st.st_mode);
    }

    static bool IsRegular(const std::string &filename)// 判断一个文件是否是一个普通文件
    {
        struct stat st;
        int ret = stat(filename.c_str(),&st);
        if(ret < 0)
        {
            return false;
        }
        return S_ISREG(st.st_mode);
    }

    static bool ValidPath(const std::string &path)// 判断一个路径是否是合法路径
    {
        // 规定：只能获取"Http.hpp"所属的目录以及更深层的目录中的资源
        std::vector<std::string> subdir;
        Split(path,"/",&subdir);// 以"/"分割字符串
        int level = 0;// 计算层数
        for(auto &dir:subdir)
        {
            if(dir == "..")// 如果碰到了要返回上层目录
            {
                --level;
                if(level < 0) return false;// 如果已经返回到了当前目录的山一层目录
                continue;
            }
            ++level;
        }
        return true;
    }
};
/*-----------------------------------------------------------------------------------------------------*/

/*-------------------------------HttpRequst模块---------------------------------------------
作用：将HTTP的请求结构化，当中保存一些请求方法、资源路径、协议版本等等内容，并提供一些控制接口*/
class HttpRequest
{
public:
    std::string _method;// 请求方法
    std::string _path;// 资源路径
    std::string _version;// 协议版本
    std::string _body;// 请求正文
    std::smatch _mathes;// 资源路径的正则提取数据
    std::unordered_map<std::string,std::string> _headers;// 头部字段，例如Content-Legth: 100,Content-Length作为key，100作为val
    std::unordered_map<std::string,std::string> _params;// 查询字符串,例如user=xxx,user作为key，xxx作为val
public:
    HttpRequest()
        :_version("HTTP/1.1")// 默认协议版本
    {}

    void Reset()// 重置
    {
        _method.clear();
        _path.clear();
        _version = "HTTP/1.1";
        _body.clear();
        std::smatch match;
        _mathes.swap(match);
        _headers.clear();
        _params.clear();
    }

    void SetHeader(const std::string &key,const std::string &val)// 插入头部字段
    {
        _headers.insert(std::make_pair(key,val));
    }

    bool HasHeader(const std::string &key) const// 判断是否存在指定的头部字段
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
        {
            return false;
        }
        return true;
    }

    std::string GetHeader(const std::string &key) const// 获取头部字段
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
        {
            return "";
        }
        return it->second;
    }

    void SetParam(const std::string &key,const std::string &val)// 插入查询字符串
    {
        _params.insert(std::make_pair(key,val));
    }

    bool HasParam(const std::string &key) const// 判断是否有指定的查询字符串
    {
        auto it = _params.find(key);
        if(it == _params.end())
        {
            return false;
        }
        return true;
    }

    std::string GetParam(const std::string &key) const// 获取指定的查询字符串
    {
        auto it = _params.find(key);
        if(it == _params.end())
        {
            return "";
        }
        return it->second;
    }

    size_t ContentLength() const// 获取请求的正文长度
    {
        bool ret = HasHeader("Content-Length");
        if(ret == false)
        {
            return 0;
        }
        std::string clen = GetHeader("Content-Length");
        return std::stol(clen);
    }

    bool Close() const// 判断这个请求是不是短连接请求
    {
        if(HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
        {
            return false;// 如果存在长连接字段，那么就不是短连接
        }
        return true;
    }
};
/*-------------------------------------------------------------------------------------------------*/

/*---------------------------------------HttpResponse模块-----------------------------------------------
作用：将HTTP响应结构化，其中包括响应状态码、正文.....并且提供一些控制接口*/
class HttpResponse
{
public:
    /*HTTP协议版本在请求当中有，不需要进行设置*/
    int _statu;// 响应状态码
    bool _redirect_flag;// 是否重定向
    std::string _body;// 响应正文
    std::string _redirect_url;// 重定向后的url
    std::unordered_map<std::string,std::string> _headers;// 头部字段
public:
    HttpResponse()
        :_redirect_flag(false),_statu(200)// 默认情况下，不启动重定向并且响应状态为OK
    {}

    HttpResponse(int statu)
        :_redirect_flag(false),_statu(statu)
    {}

    void Reset()// 重置
    {
        _statu = 200;
        _redirect_flag = false;
        _body.clear();
        _redirect_url.clear();
        _headers.clear();
    }

    void SetHeader(const std::string &key,const std::string &val)// 插入头部字段
    {
        _headers.insert(std::make_pair(key,val));
    }

    bool HasHeader(const std::string &key)// 是否存在指定的头部
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
        {
            return false;
        }
        return true;
    }

    std::string GetHeader(const std::string &key)// 获取指定的头部字段
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
        {
            return "";
        }
        return it->second;
    }

    // 设置响应正文，设置响应正文时，必须顺带设置响应正文的类型
    void SetContent(const std::string &body,const std::string &type = "text/html")
    {
        _body = body;
        SetHeader("Content-Type",type);
    }

    void SetRedirect(const std::string &url,int statu = 302)// 设置重定向的url，默认为临时重定向
    {
        _statu = statu;
        _redirect_flag = true;
        _redirect_url = url;
    }

    bool Close()// 判断这个响应是不是短连接请响应
    {
        if(HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
        {
            return false;// 如果存在长连接字段，那么就不是短连接
        }
        return true;
    }
};
/*---------------------------------------------------------------------------------------------------*/

/*--------------------------------------------HttpContext模块---------------------------------------------
作用：处理HTTP请求接收的过程，使用状态机和正则表达式来进行控制和解析*/
typedef enum 
{
    RECV_HTTP_ERROR,// 接收过程中发生错误
    RECV_HTTP_LINE,// 接收请求行
    RECV_HTTP_HEAD,// 接收请求头部
    RECV_HTTP_BODY,// 接收请求正文
    RECV_HTTP_OVER// 接收结束
}HttpRecvStatu;
#define MAX_LINE 8192// 一行数据的最大长度
class HttpContext
{
private:
    bool RecvHttpLine(Buffer *buf)// 接收HTTP请求的请求行
    {   
        if(_recv_statu != RECV_HTTP_LINE) return false;// 状态不符
        std::string line = buf->GetLineAndPop();// 从Buffer中获取一行数据
        if(line.size() == 0)// 如果并没有读取到一行完整的数据
        {
            if(buf->ReadAbleSize() > MAX_LINE)// 如果缓冲区的可读数据已经超过了单行的最大长度还不足一行，就说明出问题了
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;// URI TOO LONG
                return false;
            }
            return true;// 否则就是Buffer当中真的没有一行完整的数据，下一次进来再接收
        }
        if(line.size() > MAX_LINE)// 如果接收到一行数据大于最大单行数据的长度，也是有问题的
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 414;
            return false;
        }
        
        bool ret = ParseHttpLine(line);// 读取到了完整的一行请求行，进行解析
        if(ret == false)
        {
            return false;
        }
        _recv_statu = RECV_HTTP_HEAD;// 请求行处理完毕，可以接收请求头部
        return true;
    }

    bool ParseHttpLine(const std::string &line)// 解析HTTP请求行
    {
        std::smatch matches;
        std::regex e("(GET|HEAD|POST|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?",std::regex::icase);// 无视大小写
        bool ret = std::regex_match(line,matches,e);// 匹配的结果放到matches当中去
        if(ret == false)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400;// 给的请求有问题
            return false;
        }

        _request._method = matches[1];// 获得请求方法
        // [begin(),end()]范围内的所有字符都转换成大写
        std::transform(_request._method.begin(),_request._method.end(),_request._method.begin(),::toupper);
        _request._path = Util::UrlDecode(matches[2],false);// 进行URL解码
        _request._version = matches[4];// HTTP协议版本

        // 处理查询字符串
        std::vector<std::string> query_string_array;
        std::string query_string = matches[3];
        Util::Split(query_string,"&",&query_string_array);// 进行字符串分割解析
        for(auto &str:query_string_array)
        {
            size_t pos = str.find("=");
            if(pos == std::string::npos)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 400;// 解析失败，说明URL的查询字符串格式有问题
                return false;
            }
            std::string key = Util::UrlDecode(str.substr(0,pos),true);
            std::string val = Util::UrlDecode(str.substr(pos + 1),true);
            _request.SetParam(key,val);
        }
        return true;
    }

    bool RecvHttpHead(Buffer *buf)// 接收HTTP请求头部
    {
        if(_recv_statu != RECV_HTTP_HEAD) return false;// 判断状态
        while(true)
        {
            std::string line = buf->GetLineAndPop();
            if(line.size() == 0)
            {
                if(buf->ReadAbleSize() > MAX_LINE)
                {
                    _recv_statu = RECV_HTTP_ERROR;
                    _resp_statu = 414;
                    return false;
                }
                return true;
            }
            if(line.size() > MAX_LINE)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;
                return false;
            }
            if(line == "\n" || line == "\r\n") break;// 读取到了空行就结束头部读取
            bool ret = ParseHttpHead(line);// 读取到一行头部，就进行一行头部的解析
            if(ret == false)
            {
                return false;
            }
        }
        _recv_statu = RECV_HTTP_BODY;
        return true;
    }

    bool ParseHttpHead(std::string &line)// 解析每一行的HTTP请求头部
    {
        if(line.back() == '\n') line.pop_back();
        if(line.back() == '\r') line.pop_back();
        size_t pos = line.find(": ");
        if(pos == std::string::npos)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400;
            return false;
        }
        std::string key = line.substr(0,pos);
        std::string val = line.substr(pos + 2);
        _request.SetHeader(key,val);
        return true;
    }

    bool RecvHttpBody(Buffer *buf)// 读取HTTP请求正文
    {
        if(_recv_statu != RECV_HTTP_BODY) return false;
        size_t content_length = _request.ContentLength();// 先确定请求正文有多少长度'
        if(content_length == 0)
        {
            _recv_statu = RECV_HTTP_OVER;// 没有正文就直接接收请求完毕了
            return true;
        }
        size_t real_len = content_length - _request._body.size();// 还要读取多少长度的数据
        if(buf->ReadAbleSize() >= real_len)// 如果缓冲区的数据大小足够
        {
            _request._body.append(buf->ReadPosition(),real_len);
            buf->OffsetReader(real_len);
            _recv_statu = RECV_HTTP_OVER;
            return true;
        }
        // 到这里就是缓冲区的数据不够real_len，还要进行下一次读取，所以状态没有发生改变
        _request._body.append(buf->ReadPosition(),buf->ReadAbleSize());
        buf->OffsetReader(buf->ReadAbleSize());
        return true;
    }
public:
    HttpContext()
        :_resp_statu(200),_recv_statu(RECV_HTTP_LINE)// 默认情况下响应状态码200，从请求行开始接收
    {}

    void Reset()
    {
        _resp_statu = 200;
        _recv_statu = RECV_HTTP_LINE;
        _request.Reset();
    }

    int RespStatu() {return _resp_statu;}// 返回响应状态码

    HttpRecvStatu RecvStatu() {return _recv_statu;}// 获取当前的读取状态

    HttpRequest &GetRequest() {return _request;}// 获取设置好的请求对象

    // 接收解析HTTP请求
    void RecvHttpRequest(Buffer *buf)// 接受到的请求信息会放在Buffer当中
    {
        // 根据不同的状态做不同的事情，实际上就是一个状态机
        switch(_recv_statu)
        {
            case RECV_HTTP_LINE :RecvHttpLine(buf);
            case RECV_HTTP_HEAD :RecvHttpHead(buf);
            case RECV_HTTP_BODY :RecvHttpBody(buf);
        }
    }
private: 
    int _resp_statu;// 响应状态码，因为接收、解析过程中会出错，出错就要设置响应状态码
    HttpRecvStatu _recv_statu;// 当前读取到哪个阶段了
    HttpRequest _request;// HTTP请求对象,进行结构化
};
/*------------------------------------------------------------------------------------------*/

/*-------------------------------------------HttpServer模块------------------------------------------
作用：搭建一个HTTP服务器*/
#define DEFAULT_TIMEOUT 120// 默认定时时间，120s
class HttpServer
{
private:    
    using Handler = std::function<void(const HttpRequest &,HttpResponse *)>;// 回调函数
    using Handlers = std::vector<std::pair<std::regex,Handler>>;// 保存Handler的容器

    void OnConnected(const PtrConnection &conn)// 连接建立成功后的回调函数
    {
        conn->SetContext(HttpContext());// 给Connection对象一个协议上下文
        //DEBUG_LOG("%d号连接连接成功！并且设置了上下文！",conn->GetFd());
    }

    void ErrorHandler(const HttpRequest &req,HttpResponse *resp)// 错误处理，响应一个HTML页面即可
    {
        std::string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
        body += "</head>";
        body += "<body>";
        body += "<h1>";
        body += std::to_string(resp->_statu);
        body += " ";
        body += Util::StatuDesc(resp->_statu);
        body += "</h1>";
        body += "</body>";
        body += "</html>";
        resp->SetContent(body,"text/html");// 将响应正文设置到resp中
    }
    
    void WriteResponse(const PtrConnection &conn,const HttpRequest &req,HttpResponse &resp)// 发送响应信息
    {
        if(req.Close() == true)// 如果是短连接，就设置短连接的头部
            resp.SetHeader("Connection","close");
        else // 长连接就设置长连接的头部
            resp.SetHeader("Connection","keep-alive");
        
        if(resp._body.empty() == false && resp.HasHeader("Content-Length") == false)// 如果没有正文长度字段
            resp.SetHeader("Content-Length",std::to_string(resp._body.size()));
        if(resp._body.empty() == false && resp.HasHeader("Content-Type") == false)// 如果没有正文类型字段
            resp.SetHeader("Content-Type","application/octet-stream");
        if(resp._redirect_flag == true)// 如果设置了重定向
            resp.SetHeader("Location",resp._redirect_url);

        // 组织响应字符串
        std::string resp_str;
        resp_str += req._version + " " + std::to_string(resp._statu) + " " + Util::StatuDesc(resp._statu) + "\r\n";// 响应行
        for(auto &head:resp._headers)// 响应头
        {
            resp_str += head.first + ": " + head.second + "\r\n";
        }
        resp_str += "\r\n";// 空行
        resp_str += resp._body;// 正文
        conn->Send(resp_str.c_str(),resp_str.size());
    }

    bool IsFileHandler(const HttpRequest &req)// 判断一个HTTP请求是否是静态资源请求
    {
        if(_basedir.empty()) return false;// 如果没有设置静态资源根目录
        if(req._method != "GET" && req._method != "HEAD") return false;// 如果不是GET或HEAD方法
        if(Util::ValidPath(req._path) == false) return false;// 如果不是一个有效的请求路径

        std::string req_path = _basedir + req._path;
        if(req._path.back() == '/') req_path += "index.html";// 如果请求的资源是一个目录
        if(Util::IsRegular(req_path) == false) return false;// 请求路径和静态资源根目录合并后依然不是一个合法路径
        return true;
    }

    void FileHandler(const HttpRequest &req,HttpResponse *resp)// 处理静态资源请求
    {
        std::string req_path = _basedir + req._path;
        if(req._path.back() == '/') req_path += "index.html";
        bool ret = Util::ReadFile(req_path,&resp->_body);// 将HTTP请求当中的指定的路径中的资源读取到响应的正文当中
        if(ret == false) return;
        std::string mime = Util::ExtMime(req_path);// 根据请求资源的后缀名获得mime，以填充响应头部
        resp->SetHeader("Content-Type",mime);
    }

    void Dispatcher(HttpRequest &req,HttpResponse *resp,Handlers &handlers)// 功能性请求的处理
    {
        // 在对应请求方法的回调函数容器中，查找是否有对应的处理函数
        for(auto &handler:handlers)
        {
            const std::regex &re = handler.first;
            const Handler &functor = handler.second;
            bool ret = std::regex_match(req._path,req._mathes,re);
            if(ret == false) continue;
            return functor(req,resp);
        }
        resp->_statu = 404;
    }

    void Route(HttpRequest &req,HttpResponse *resp)
    {
        if(IsFileHandler(req) == true)
        {
            FileHandler(req,resp);
            return;
        }

        // 如果不是静态资源请求，那就是有别的任务
        if(req._method == "GET" || req._method == "HEAD")
            return Dispatcher(req,resp,_get_route);
        else if(req._method == "POST")
            return Dispatcher(req,resp,_post_route);
        else if(req._method == "PUT")
            return Dispatcher(req,resp,_put_route);
        else if(req._method == "DELETE")
            return Dispatcher(req,resp,_delete_route);
        resp->_statu = 405;
    }

    void OnMessage(const PtrConnection &conn,Buffer *buf)
    {
        while(buf->ReadAbleSize() > 0)// 如果缓冲区当中的可读数据一直存在，那么就一直进行数据读取
        {
            HttpContext *context = conn->GetContext()->get<HttpContext>();// 获取连接的协议上下文
            context->RecvHttpRequest(buf);// 从buf当中读取HTTP请求
            HttpRequest &req = context->GetRequest();// 读取完毕之后，拿到请求

            HttpResponse resp(context->RespStatu());// 构造出响应对象
            if(context->RespStatu() >= 400)// 响应状态码是有错误的
            {
                ErrorHandler(req,&resp);// 返回一个错误页面
                WriteResponse(conn,req,resp);// 发送响应
                context->Reset();// 重置上下文
                buf->OffsetReader(buf->ReadAbleSize());
                conn->Shutdown();// 关闭连接
                return;
            }
            if(context->RecvStatu() != RECV_HTTP_OVER)
            {
                return;// 如果HTTP请求还没有读完，说明不能处理，因为请求不完整
            }
            Route(req,&resp);
            WriteResponse(conn,req,resp);
            context->Reset();// 发送完毕之后重置上下文
            if(resp.Close() == true) conn->Shutdown();
        }
    }
public:
    HttpServer(int port,int timeout = DEFAULT_TIMEOUT)
        :_server(port)
    {
        _server.EnableInactiveRelease(timeout);
        _server.SetConnectedCallback(std::bind(&HttpServer::OnConnected,this,std::placeholders::_1));
        _server.SetMessgageCallback(std::bind(&HttpServer::OnMessage,this,std::placeholders::_1,std::placeholders::_2));
    }

    void SetBaseDir(const std::string &path)// 设置静态资源根目录
    {
        if(Util::IsDirectory(path) == false) abort();// 如果设置的根目录不是一个合法的路径
        _basedir = path;
    }

    void Get(const std::string &pattern,const Handler &handler)// 设置GET方法的回调函数
    {
        _get_route.push_back(std::make_pair(std::regex(pattern),handler));
    }

    void Post(const std::string &pattern,const Handler &handler)// 设置POST方法的回调函数
    {
        _post_route.push_back(std::make_pair(std::regex(pattern),handler));
    }

    void Put(const std::string &pattern,const Handler &handler)// 设置PUT方法的回调函数
    {
        _put_route.push_back(std::make_pair(std::regex(pattern),handler));
    }

    void Delete(const std::string &pattern,const Handler &handler)// 设置DELETE方法的回调函数
    {
        _delete_route.push_back(std::make_pair(std::regex(pattern),handler));
    }

    void SetThreadCount(int count)// 设置线程数量
    {
        _server.SetThreadCount(count);
    }

    void Start()// 启动HTTP服务器
    {
        _server.Start();
    }
private:  
    Handlers _get_route;// GET方法的回调函数容器
    Handlers _post_route;// POST方法的回调函数容器
    Handlers _put_route;// PUT方法的回调函数容器
    Handlers _delete_route;// DELETE方法的回调函数容器
    std::string _basedir;// 静态资源根目录
    TcpServer _server;// 网络库组件 
};


